//
//  ShopHomeViewController.m
//  OrderSeat
//
//  Created by wangwei on 13-10-5.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "ShopHomeViewController.h"
#import "ShopCommentCell.h"
#import "ShopDetailViewController.h"
#import "ShopCommentsViewController.h"
#import "TakePhotoViewController.h"
#import "PostCommentViewController.h"
#import "CorrectionViewController.h"
#import "SelectDishViewController.h"
#import "SeatViewController.h"
#import "PhotoViewController.h"
#import "UIImageView+WebCache.h"
#import "RelationSeatViewController.h"
#import "ComfirmOrderNoSeatViewController.h"
#import "GourmetDetailViewController.h"
#import "CouponDetailViewController.h"
#import "PostCommentViewController.h"
#import "MapViewController.h"
#import "LoginViewController.h"
#import "Place.h"
#import "CommUtil.h"
#import "DbManager.h"

#define LIKE_FORMAT @"喜欢  (%@)"
#define FAVORITES_FORMAT @"收藏  (%@)"
#define COMM_FORMAT @"共有%@条订单/%@条餐后点评"
#define COUPON_TAG 1
#define GOURMET_TAG 2

@implementation ShopHomeViewController

#pragma 初始化函数
- (id)initWithId:(NSString *)shopId
{
    self = [super initWithNibClass:[ShopHomeViewController class]];
    if (self) {
        self.shopId = shopId;
        self.controls = [NSMutableDictionary dictionaryWithCapacity:10];
        self.viewControllers = [NSMutableDictionary dictionaryWithCapacity:5];
        _dataSource = [[ShopHomeDataSource alloc] initWithVC:self];
    }
    return self;
}

#pragma 视图加载完成
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupUI];
    [_dataSource fetchShopInfoWithId:_shopId];
}

#pragma 初始化UI工作
- (void)setupUI
{
    [self createLeftButton];
    [self createRightButton:@"分享"];
    [self setNavigationTitle:@"商家信息"];
    
    self.commentsTable.delegate = _dataSource;
    self.commentsTable.dataSource = _dataSource;
    
    [UIView hiddensYES:@[_theScrollview]];
}

#pragma 视图显示完成
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.isBack) {
        [[AppDelegate sharedInstance].tabBarController selectedTabAtIndex:1];
        self.isBack = NO;
    }
}

#pragma 导航栏返回按钮事件
- (void)leftButtonClick:(id)sender
{
    [AppDelegate changeToNormalTabBar];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightButtonClick:(id)sender
{
    NSString *imageURL = [self.data objectForKey:@"fximage"];
    NSString *content = [self.data objectForKey:@"fenxiang"];
    NSString *link = [self.data objectForKey:@"fxlink"];
    
    [AppDelegate shareWithContent:content andImageURL:imageURL andLink:link];
}

#pragma 预定座位按钮事件
- (IBAction)orderSeatClick:(id)sender
{
//    if (![AppDelegate checkLoginWithDelegate:self]) return;
    
    SeatViewController *seatVC = [[SeatViewController alloc] initWithShopId:self.shopId];
    seatVC.data = self.data;
    
    [self.navigationController pushViewController:seatVC animated:YES];
}

#pragma 点菜按钮事件
- (IBAction)selectDishClick:(id)sender
{
//    if (![AppDelegate checkLoginWithDelegate:self]) return;
    [_dataSource checkHaveSeat];
}

#pragma 喜欢按钮事件
- (IBAction)lickAction:(id)sender
{
    if (_btnXihuan.selected) {
        [AppDelegate showMessage:@"亲，每天只能喜欢一次吆"];
        return;
    }
    [_dataSource like:self.shopId];
}

#pragma 收藏按钮事件
- (IBAction)favoritesAction:(id)sender
{
    if (![AppDelegate checkLoginWithDelegate:self]) return;
    
    if (_btnShoucang.selected) {
        [AppDelegate showMessage:@"亲，您已经收藏过了"];
        return;
    }
    
    [_dataSource favorites:self.shopId username:[AppSetting userName]];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    loginVC.backController = self;
    [self.navigationController pushViewController:loginVC animated:YES];
}

#pragma tabbar栏视图导航切换
- (void)selectedTab:(UIButton *)button
{
    NSArray *buttons = [AppDelegate sharedInstance].tabBarController.buttons;
    for (UIButton *btn in buttons) {
        btn.selected = btn.tag == button.tag;
    }
    
    switch (button.tag) {
        case 0:{            
            [self pushViewController:[ShopDetailViewController class]];
            break;
        }
        case 1:{            
            [self pushViewController:[PhotoViewController class]];
            break;
        }
        case 2:{
            [self pushViewController:[TakePhotoViewController class]];
            break;
        }
        case 3:{
            [self pushViewController:[ShopCommentsViewController class]];
            break;
        }
        case 4:{
            [self pushViewController:[CorrectionViewController class]];
            break;
        }
    }
}

#pragma 从导航视图中查找是否已经存在的该视图，如果存在则直接pop过去，不存在则先创建再push过去
- (void)pushViewController:(Class)class
{
    NSString *key = NSStringFromClass(class);
    UIViewController *viewController = [self.viewControllers objectForKey:key];
    
    //如果已创建过该视图，且导航中存在该视图，则先拿到该视图，并从当前视图导航pop到该视图
    if ([self.viewControllers objectForKey:key] && [self findController:[self.viewControllers objectForKey:key]]) {
        [self.navigationController popToViewController:viewController animated:NO];
    }
    //如果已创建该视图，且导航中不存在该视图，则先拿到该视图，并从当前视图导航push到该视图
    else if([self.viewControllers objectForKey:key] && ![self findController:[self.viewControllers objectForKey:key]]){
        [self.navigationController pushViewController:viewController animated:NO];
    }
    //如果没有创建过该视图或者导航中不存在该视图，那么从新创建该视图，并且从当前视图导航push到该视图
    else {
        id vController = [[class alloc] initWithShopId:self.shopId];
        [vController setParentController:self];
        
        NSString *photoClass = NSStringFromClass([PhotoViewController class]);
        if ([key isEqualToString:photoClass]) {
            ((PhotoViewController *)vController).isShop = YES;
        }
        
        [self.navigationController pushViewController:vController animated:NO];
        [self.viewControllers setObject:vController forKey:key];
    }
    
    if ([viewController isKindOfClass:[TakePhotoViewController class]]) {
        TakePhotoViewController *takePhotoVC = [self.viewControllers objectForKey:key];
        [takePhotoVC showActionSheet];
    }
}

- (IBAction)mapNavigationAction:(id)sender
{
    MapViewController *mapVC = [[MapViewController alloc] initWithShopInfo:self.data];
    [self.navigationController pushViewController:mapVC animated:YES];
}

#pragma 拨打电话
- (IBAction)callPhoneAction:(id)sender
{
    NSString *tel = _phoneLabel.titleLabel.text;
    tel = [NSString stringWithFormat:@"tel:%@", tel];
    
    UIWebView *callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:tel];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];

    [self.view addSubview:callWebview];
}

#pragma 根据状态跳转到不同的页面，状态1:已预定座位，跳转到关联座位页面
#pragma 状态2:没有预定座位，跳转到点菜页面
- (void)goForState:(int)state
{
    if (state == 1) {
        RelationSeatViewController *comfirmVC = [[RelationSeatViewController alloc] initWithShopId:_shopId];
        [self.navigationController pushViewController:comfirmVC animated:YES];
    }
    if (state == 2) {
        SelectDishViewController *selectDishVC = [[SelectDishViewController alloc] initWithShopId:_shopId];
        [self.navigationController pushViewController:selectDishVC animated:YES];
    }
}

#pragma 按钮操作完成后的工作,例如点击了喜欢按钮，设置按钮状态，标题喜欢数，保存记录
- (void)opration:(OprationType)type count:(NSString *)count
{
    if (type == Like) {
        NSString *likeText = [NSString stringWithFormat:LIKE_FORMAT, count];
        _btnXihuan.selected = YES;
        [_btnXihuan setTitleForNormal:likeText];
        [[DbManager sharedManager] insertLike:_shopId type:ShopLikeType];
    }
    
    if (type == Favorites) {
        NSString *favText = [NSString stringWithFormat:FAVORITES_FORMAT, count];
        [_btnShoucang setTitleForNormal:favText];
        _btnShoucang.selected = YES;
    }
}

#pragma 请求返回餐馆信息，并填充到视图上
- (void)setFormValues:(NSDictionary*)data
{
    self.data = [NSMutableDictionary dictionaryWithDictionary:data];
    CLog(@"self.data:%@",self.data);
    
    BOOL isFav = [[data objectForKey:@"ifshoucang"] intValue] > 0;
    
    NSString *favText = [data objectForKey:@"shoucang"];
    NSString *likeText = [data objectForKey:@"xihuan"];
    NSString *commCount = [data objectForKey:@"pinglunshu"];
    NSString *orderCount = [data objectForKey:@"dingdanshu"];
    NSString *commText = [NSString stringWithFormat:COMM_FORMAT,orderCount,commCount];
    NSDictionary *cuxiaoDic = [data objectForKey:@"cuxiao"];
    NSDictionary *meishiDic = [data objectForKey:@"meishi"];
    
    //这个接口加了三个key,fenxiang是分享的内容， fximage是分享的图片地址，fxlink是分享信息点击的链接地址
    
    favText = [NSString stringWithFormat:FAVORITES_FORMAT, favText];
    likeText = [NSString stringWithFormat:LIKE_FORMAT, likeText];
    
    [self addControl:_btnShoucang value:favText forKey:@"shoucang"];
    [self addControl:_btnXihuan value:likeText forKey:@"xihuan"];
    [self addControl:_shopNameLabel forKey:@"name"];
    [self addControl:_fuwuLabel forKey:@"fuwu"];
    [self addControl:_kouweiLabel forKey:@"kouwei"];
    [self addControl:_huanjingLabel forKey:@"huanjing"];
    [self addControl:_zhekouLabel forKey:@"zhekou"];
    [self addControl:_caixiLabel forKey:@"caixi"];
    [self addControl:_addressLabel forKey:@"xianqu"];
    [self addControl:_phoneLabel forKey:@"tel"];
    [self addControl:_logoIV forKey:@"logo"];
    
    _btnShoucang.selected = isFav;//搜藏按钮是否选中
    _secondView.hidden = [cuxiaoDic isNullOrEmpty];//是否隐藏活动视图
    _thridView.hidden = [meishiDic isNullOrEmpty];//是否隐藏美食视图
    
    if (!_secondView.hidden) {
        NSString *title = [cuxiaoDic objectForKey:@"title"];
        [self addControl:_huodongLabel value:title forKey:@"cuxiao_title"];
        //添加点击活动事件
        [_secondView addTarget:self action:@selector(tapAction:) forTag:COUPON_TAG];
    }
    
    if (!_thridView.hidden) {
        NSString *url = [meishiDic objectForKey:@"tp"];
        [self addControl:_tuijianLogo value:url forKey:@"tp"];
        
        NSString *nr = [meishiDic objectForKey:@"nr"];
        if ([nr length] > 40) nr = [[nr substringToIndex:40] stringByAppendingString:@"..."];
        NSString *title = [meishiDic objectForKey:@"title"];
        [self addControl:_tuijianNameLabel value:title forKey:@"meishi_title"];
        [self addControl:_tuijianContentLabel value:nr forKey:@"meishi_nr"];
        //添加点击美食事件
        [_thridView addTarget:self action:@selector(tapAction:) forTag:GOURMET_TAG];
    }
    
    [self addControl:_commCountLabel value:commText forKey:@"comment_title"];
    [_tableHeader addTarget:self action:@selector(composeAction:)];
    
    //设置控件的值
    [UIView setTexts:self.data forControls:self.controls];
    [self reLayoutSubviews];
}

- (void)composeAction:(id)sender
{
    if(![AppDelegate checkLoginWithDelegate:self]) return;
    
    PostCommentViewController *composeVC = [[PostCommentViewController alloc] initWithShopId:_shopId];
    [self.navigationController pushViewController:composeVC animated:YES];
}

#pragma 跳转到促销活动和美食页面，这里的事件来自促销活动和美食的视图
- (void)tapAction:(id)sender
{
    if ([sender tag] == COUPON_TAG) {
        NSDictionary *coupon = [self.data objectForKey:@"cuxiao"];
        NSString *couponId = [coupon objectForKey:@"id"];
        CouponDetailViewController *couponVC = [[CouponDetailViewController alloc] initWithCouponId:couponId];
        [self.navigationController pushViewController:couponVC animated:YES];
    }
    
    if ([sender tag] == GOURMET_TAG) {
        NSDictionary *gourmet = [self.data objectForKey:@"meishi"];
        NSString *gourmetId = [gourmet objectForKey:@"id"];
        GourmetDetailViewController *gourmetVC = [[GourmetDetailViewController alloc] initWithId:gourmetId];
        [self.navigationController pushViewController:gourmetVC animated:YES];
    }
}

#pragma 重新调整视图的位置和高度
- (void)reLayoutSubviews
{
    _btnXihuan.selected = [[DbManager sharedManager] isLike:_shopId type:ShopLikeType];
    
    [UIView hiddenNO:@[_theScrollview]];
    [UIView drawBorders:@[_firstView, _secondView, _thridView, _lastView]];
    [UIView autoHeights:@[_huodongLabel, _tuijianContentLabel]];
    [UIView autoHeights:@[_firstView, _secondView, _thridView,_commentsTable, _lastView]];
    [UIView autoLayoutVertical:@[_firstView, _secondView, _thridView, _lastView]];
    
    _theScrollview.height = ScreenHeight - StatusBarHeight - NavBarHeight - TabBarHeight;
    [self.theScrollview autoHeight];
}

@end

//=========================================================================================
#pragma ===================数据源类实现======================================================
//=========================================================================================

@implementation ShopHomeDataSource

#define FETCH_SHOP_INFO_TAG 11
#define SHOP_LIKE_TAG       12
#define SHOP_FAVORITES_TAG  13
#define CHECK_HAVE_SEAT_TAG 14
#define SHOP_SHARE_TAG 15
#define cellId @"ShopCommentCell"

- (id)initWithVC:(id)viewController
{
    self = [super init];
    if (self) {
        self.viewController = viewController;
        _commentsList = [[NSArray alloc] init];
        self.commentCell = [_viewController createCellWithNib:cellId];
    }
    return self;
}

#pragma 获取餐厅信息
- (void)fetchShopInfoWithId:(NSString *)shopId
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_SHOP_INFO, shopId,[AppSetting userName]];
    [self get:url tag:FETCH_SHOP_INFO_TAG];
}

#pragma 喜欢
- (void)like:(NSString*)shopId
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_SHOP_LIKE, shopId];
    [self get:url tag:SHOP_LIKE_TAG];
}

#pragma 收藏
- (void)favorites:(NSString*)shopId username:(NSString*)username
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_SHOP_FAVORITES, shopId,username];
    [self get:url tag:SHOP_FAVORITES_TAG];
}

#pragma 检查是否有座位
- (void)checkHaveSeat
{
    [SVProgressHUD show];
    NSString *url = [NSString stringWithFormat:API_CHECK_HAVE_SEAT, _viewController.shopId,[AppSetting userName]];
    [self get:url tag:CHECK_HAVE_SEAT_TAG];
}

#pragma 请求返回结果
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [SVProgressHUD dismiss];
    NSDictionary *json = [request.responseData JSONValue];
    NSDictionary *data = [json objectForKey:@"data"];
    
    if (request.tag == FETCH_SHOP_INFO_TAG) {
        self.shopInfoDic = data;
        self.commentsList = [self.shopInfoDic objectForKey:@"pinglun"];
        
        [_viewController.commentsTable reloadData];
        [_viewController setFormValues:self.shopInfoDic];
    }
    
    if (request.tag == SHOP_LIKE_TAG) {
        int state = [[data objectForKey:@"state"] intValue];
        if (state == 1) {
            NSString* likeCount = [data objectForKey:@"xihuan"];
            [_viewController opration:Like count:likeCount];
        }
    }
    
    if (request.tag == SHOP_FAVORITES_TAG) {
        int state = [[data objectForKey:@"state"] intValue];
        if (state == 1) {
            NSString* favCount = [data objectForKey:@"shoucang"];
            [_viewController opration:Favorites count:favCount];
        }
        else if (state == 2) {
            [AppDelegate showMessage:@"您已经收藏过了"];
        }
        else if(state == 3) {
            [AppDelegate showMessage:@"对不起，您还没有登录，请登录后再收"];
        }
    }
    
    if (request.tag == CHECK_HAVE_SEAT_TAG) {
        int state = [[json objectForKey:@"state"] intValue];
        [_viewController goForState:state];
    }
}

#pragma ===================加载tableview数据 Begin==========================================

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    NSDictionary *dic = [self.commentsList objectAtIndex:indexPath.row];
    return [self.commentCell getCellHeight:dic];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _commentsList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellId = @"ShopCommentCell";
    ShopCommentCell *cell = [self.viewController createCellWithNib:CellId tableview:tableView];
    
    NSDictionary *dic = [_commentsList objectAtIndex:indexPath.row];
    [cell setContent:dic];
    
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopCommentsViewController *commentsVC = [[ShopCommentsViewController alloc] initWithShopId:_viewController.shopId];
    [_viewController.navigationController pushViewController:commentsVC animated:YES];
}

@end

